<template>
  <view class="page price-adjust-page">
    <view class="form-view">
      <view class="form-item form-pa20 clearfix">
        <view class="float_left form-label">
          商铺
          <text class="icon-requird">*</text>
        </view>
        <view class="float_right form-value">
          <text class="input-pl" v-if="!goods_item.shopName">请选择</text>
          <text v-else>{{ goods_item.shopName }}</text>
        </view>
      </view>
      <view class="goods-ul b20">
        <view class="goods-item">
          <view class="clearfix goods-goods">
            <!-- <view class="float_left goods-img"><image :src="goods_item.images[0]" mode="aspectFill"></image></view> -->
            <view class="float_left goods-cont-right">
              <view class="goods-tit ellipsis">{{ goods_item.title }}</view>
              <view class="goods-info">
                <text class="gi-label">编号：</text>
                <text class="gi-value">{{ goods_item.code }}</text>
              </view>
              <view class="goods-info">
                <text class="gi-label">品牌：</text>
                <text class="gi-value">{{ goods_item.brandName }}</text>
              </view>
              <view class="goods-info">
                <text class="gi-label">分类：</text>
                <text class="gi-value">{{ goods_item.categoryName }}</text>
              </view>
            </view>
          </view>
          <block
            v-for="(itemP, indexP) in goods_item.specMultiple"
            :key="indexP"
          >
            <view class="form-item form-pa20 b20 clearfix">
              <view class="float_left form-label">规格</view>
              <view class="float_right form-value">
                <text>{{ itemP.unitName }}</text>
                <block v-if="itemP.specGroup && itemP.specGroup.length">
                  <text
                    v-for="(itemU, indexU) in itemP.specGroup"
                    :key="indexU"
                  >
                    _{{ itemU.specValueName }}
                  </text>
                </block>
              </view>
            </view>
            <view class="form-item form-pa20 clearfix">
              <view class="float_left form-label">是否启用阶梯价</view>
              <view class="float_right form-value">
                <switch
                  :checked="itemP.enabledLadder === 1"
                  @change="enabledLadderChange(indexP)"
                  color="#4cd964"
                />
              </view>
            </view>
            <view class="form-up">
              <view class="form-label">
                调整价格（元）
                <text class="icon-requird">*</text>
              </view>
              <view class="form-value">
                <input
                  type="digit"
                  v-if="parseInt(itemP.enabledLadder) === 0"
                  placeholder="请输入价格"
                  placeholder-class="input-pl"
                  class="form-input"
                  v-model="itemP.salePrice"
                />
                <view v-else>
                  <ul
                    v-if="parseInt(itemP.enabledLadder) === 1"
                    class="ladder-price-ul"
                  >
                    <li
                      class="ladder-price-item"
                      v-for="(itempp, indexpp) in itemP.ladderPrice"
                      :key="indexpp"
                    >
                      <input
                        class="ladder-price-input"
                        disabled
                        :value="itempp.from"
                        style="width: 60px"
                      />
                      --
                      <input
                        type="digit"
                        class="ladder-price-input"
                        v-if="!(indexpp === itemP.ladderPrice.length - 1)"
                        v-model="itempp.to"
                        :min="itempp.from + 1"
                        @blur="ladderPriceBlur(itempp.to, indexpp, indexP)"
                        style="width: 60px"
                      />
                      <input
                        class="ladder-price-input"
                        v-else
                        disabled
                        value="∞"
                        style="width: 60px"
                      />
                      {{ itemP.unitName }}
                      <input
                        class="ladder-price-input"
                        type="digit"
                        v-model="itempp.price"
                        style="width: 80px"
                      />
                      元
                      <i
                        @click="delLadderPrice(indexpp, indexP)"
                        class="iconfont icon-shanchu del-icon"
                      ></i>
                    </li>
                    <li>
                      <button
                        @click="addLadderPrice(indexP)"
                        class="tag-item add-btn"
                        type="primary"
                        size="mini"
                      >
                        <i class="iconfont icon-xinzeng"></i>
                        新增
                      </button>
                    </li>
                  </ul>
                </view>
              </view>
            </view>
          </block>
        </view>
      </view>
    </view>
    <view class="fixed-bottom">
      <button type="primary" class="sub-btn" @click="checkSub">保存</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      user_name: uni.getStorageSync("user_name") || "", // 或直接写死 ''
      goods_item: {},
    };
  },
  onLoad(options) {
    if (options.goodsId) {
      try {
        // this.goods_item = JSON.parse(decodeURIComponent(options.goods));
        this.goods_item = {
          goodsId: options.goodsId,
        };
        this.getGoodsDetail();
      } catch (e) {
        this.$api && this.$u.toast && this.$u.toast("商品数据异常");
      }
    }
  },
  methods: {
    async getGoodsDetail() {
      // 适配当前项目接口调用方式
      const id = this.goods_item.goodsId || this.goods_item.id;
      const res = await this.$u.api.getGoodsInfo(id);
      if (res && res.data) {
        this.goods_item = res.data;
      }
    },
    checkSub() {
      let ladderPriceLength = true;
      let isLadderPrice = true;
      for (let p in this.goods_item.specMultiple) {
        let itemP = this.goods_item.specMultiple[p];
        if (itemP.enabledLadder === 1) {
          if (!itemP.ladderPrice || itemP.ladderPrice.length < 2) {
            ladderPriceLength = false;
            break;
          } else if (
            !itemP.ladderPrice.every((itemPL) => Number(itemPL.price) > 0)
          ) {
            isLadderPrice = false;
            break;
          }
        } else {
          if (!itemP.salePrice || Number(itemP.salePrice) <= 0) {
            isLadderPrice = false;
            break;
          }
        }
      }
      if (!ladderPriceLength) {
        this.$u.toast("请至少设置两条阶梯价");
        return;
      }
      if (!isLadderPrice) {
        this.$u.toast("请输入价格");
        return;
      }
      this.subData();
    },
    async subData() {
      let salePrice = {};
      for (let i in this.goods_item.specMultiple) {
        const itemS = this.goods_item.specMultiple[i];
        if (itemS.ladderPrice && itemS.ladderPrice.length) {
          itemS.ladderPrice[itemS.ladderPrice.length - 1].to = 9999999999;
        }
        salePrice[itemS.id] = {
          marketPrice: itemS.salePrice,
          salePrice: itemS.enabledLadder === 0 ? itemS.salePrice : 0,
          unitName: itemS.unitName,
          ladderPrice: itemS.enabledLadder === 0 ? [] : itemS.ladderPrice,
          enabledLadder: itemS.enabledLadder,
        };
      }
      const params = {
        createUserName: this.user_name,
        goodsName: this.goods_item.title,
        goodsId: this.goods_item.id,
        saleType: 1,
        salePriceType: 1,
        salePriceAreaType: 1,
        salePrice: salePrice,
        shopId: this.goods_item.shopId,
        shopName: this.goods_item.shopName,
      };
      uni.showLoading({ title: "提交中..." });
      const res = await this.$u.api.addAndEffective(params);
      uni.hideLoading();
      if (res && res.err) {
        this.$u.toast(res.errMsg || "提交失败");
        return;
      }
      this.$u.toast("提交成功");
      this.goPage("/pages/goods/PriceTable", "redirectTo");
    },
    delLadderPrice(index, rIndex) {
      const target = this.$_util.deepClone(this.goods_item);
      const priceData = target.specMultiple;
      if (priceData[rIndex].ladderPrice.length === 2) {
        return;
      }
      priceData[rIndex].ladderPrice.splice(index, 1);
      priceData[rIndex].ladderPrice[0].from = 1;
      priceData[rIndex].ladderPrice[
        priceData[rIndex].ladderPrice.length - 1
      ].from = Number(priceData[rIndex].ladderPrice[0].to) + 1;
      this.goods_item = target;
    },
    addLadderPrice(rIndex) {
      const target = this.$_util.deepClone(this.goods_item);
      const priceData = target.specMultiple;
      if (priceData[rIndex].ladderPrice.length === 3) {
        return;
      }
      if (!priceData[rIndex].ladderPrice.length) {
        priceData[rIndex].ladderPrice.push({
          from: 1,
          price: "",
          to: 2,
        });
      } else {
        const upL =
          priceData[rIndex].ladderPrice[
            priceData[rIndex].ladderPrice.length - 1
          ];
        priceData[rIndex].ladderPrice.push({
          from: Number(upL.to) + 1,
          price: "",
          to: Number(upL.to) + 2,
        });
      }
      this.goods_item = target;
    },
    ladderPriceBlur(val, index, rindex) {
      const target = this.$_util.deepClone(this.goods_item);
      const priceData = target.specMultiple;
      if (priceData[rindex].ladderPrice[index + 1]) {
        priceData[rindex].ladderPrice[index + 1].from = Number(val) + 1;
        if (index === 0) {
          priceData[rindex].ladderPrice[index + 1].to = Number(val) + 2;
          if (priceData[rindex].ladderPrice[index + 2]) {
            priceData[rindex].ladderPrice[index + 2].from = Number(val) + 3;
          }
        }
      }
      this.goods_item = target;
    },
    enabledLadderChange(ip) {
      const target = this.$_util.deepClone(this.goods_item);
      target.specMultiple[ip].enabledLadder =
        target.specMultiple[ip].enabledLadder === 1 ? 0 : 1;
      this.goods_item = target;
    },
  },
};
</script>

<style lang="scss">
.page.price-adjust-page {
  background: #f8f8f8;
  min-height: 100vh;
}
.form-view {
  background: #fff;
  border-radius: 12upx;
  margin: 24upx;
  padding-bottom: 24upx;
}
.form-item {
  border-bottom: 1upx solid #f0f0f0;
}
.form-item:last-child {
  border-bottom: none;
}
.form-label {
  font-size: 28upx;
  color: #333;
}
.form-value {
  font-size: 28upx;
  color: #666;
}
.input-pl {
  color: #bbb;
}
.goods-tit {
  font-weight: bold;
  font-size: 32upx;
  color: #222;
}
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.ladder-price-ul {
  padding: 0;
  margin: 0;
}
.ladder-price-item {
  display: flex;
  align-items: center;
  margin-bottom: 10upx;
}
.ladder-price-input {
  background: #f5f5f5;
  border: 1upx solid #eee;
  border-radius: 6upx;
  text-align: center;
  padding: 0 8upx;
  margin-right: 8upx;
  height: 48upx;
  line-height: 48upx;
}
.add-btn {
  margin-top: 8upx;
  background: #f0f9eb;
  color: #67c23a;
  border: none;
}
.del-icon {
  color: #f56c6c;
  margin-left: 10upx;
  font-size: 26upx;
  cursor: pointer;
}
.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
  box-shadow: 0 -2upx 8upx #eee;
  padding: 20upx 0;
  z-index: 10;
}
.sub-btn {
  width: 90%;
  margin: 0 auto;
  background: #007aff;
  color: #fff;
  border-radius: 8upx;
  font-size: 32upx;
  padding: 18upx 0;
  text-align: center;
}
</style>
